const mysql = require('mysql')
const config = require('./default')

// 创建线程池
let pool = mysql.createPool({
    host: config.dataBase.HOST,
    user: config.dataBase.USERNAME,
    password: config.dataBase.PASSWORD,
    database: config.dataBase.DATABASE,
    port: config.dataBase.PORT
})

// 连接线程池,做sql查找
let allServices = {
    query: function(sql, values) {
        return new Promise((resolve, reject) => {
            pool.getConnection(function(err, connection) {
                if(err) {
                    reject(err)
                } else { // 连接成功
                    connection.query(sql, values, (err, rows) => {
                        if(err) {
                            reject(err)
                        } else {
                            resolve(rows)
                        }
                        connection.release() // 释放连接
                    })
                }
            })
        })
    }
}

// 用户登录
let userLogin = function(phone, userpwd) {
    let _sql = `select * from users where phone="${phone}" and password="${userpwd}";`
    return allServices.query(_sql)

}

// 用户注册
let insertUser = function(value) {
    let _sql = `insert into users set phone=?,password=?,name=?;`
    return allServices.query(_sql, value)
}

// 获取店铺数据
let getshoplist = function() {
    let _sql = `select * from shopitem;`
    return allServices.query(_sql)
}

// 获取商品详情
let detaillist = function(shopid) {
    let _sql = `select * from itemlist where shoptype="${shopid}";`
    return allServices.query(_sql)
}

// 获取需要的商品id
let classifyitem = function(shopid) {
    let _sql = `select * from classify where shoptype="${shopid}";`
    return allServices.query(_sql)
}

// detail页面获取评论
let getcomment = function(shopid) {
    let _sql = `select * from comment where shoptype="${shopid}";`
    return allServices.query(_sql)
}

// 查找用户
let findUser = function(phone) {
    let _sql = `select * from users where phone="${phone}";`
    return allServices.query(_sql)
} 
module.exports = {
    userLogin,
    findUser,
    insertUser,
    getshoplist,
    detaillist,
    classifyitem,
    getcomment,
}